<template>
    <div>
        <el-card style="float: left;width: 300px;height: 360px;margin-left: 100px;">
            <div align="center" style="margin-top: 20px;">
                <el-image style="width: 100px; height: 100px" src="http://localhost:5008/Image/登录密码.jpg" />
            </div>
            <span style="font-size: 20px;margin-left:34% ;color:dimgrey;">登录密码</span>

            <h2 style="font-size: 20px;margin-left:33% ;color:greenyellow;margin-top: 20px;">√ 已设置</h2>
            <!-- <h2 v-if="" style="font-size: 20px;margin-left:38% ;color:dimgrey;margin-top: 20px;">未设置</h2> -->
            <!-- <el-button style="width: 180px;height: 45px;margin-left:15% ;margin-top: 20px; " @click="">修改</el-button> -->
            <el-button style="width: 180px;height: 45px;margin-left:15% ;margin-top: 20px; "
                @click="dialogFormVisible = true">绑定</el-button>
        </el-card>
        <el-card style="float: left;width: 300px;height: 360px;margin-left: 50px;">
            <div align="center" style="margin-top: 20px;">
                <el-image style="width: 100px; height: 100px" src="http://localhost:5008/Image/修改手机号.jpg" />
            </div>
            <span style="font-size: 20px;margin-left:32% ;color:dimgrey;">修改手机号</span>

            <h2 style="font-size: 20px;margin-left:33% ;color:greenyellow;margin-top: 20px;">√ 已设置</h2>
            <!-- <h2 style="font-size: 20px;margin-left:38% ;color:dimgrey;margin-top: 20px;">未绑定</h2> -->
            <!-- <el-button style="width: 180px;height: 45px;margin-left:15% ;margin-top: 20px; " @click="">修改</el-button> -->
            <el-button style="width: 180px;height: 45px;margin-left:15% ;margin-top: 20px; "
                @click="dialogFormVisible2 = true">绑定</el-button>
        </el-card>

    </div>
    <div style="margin-top: 20px;width: 1000px;">
        <el-card style="float: left;width: 300px;height: 360px;margin-left: 100px;margin-top: 40px;">
            <div align="center" style="margin-top: 20px;">
                <el-image style="width: 100px; height: 100px" src="http://localhost:5008/Image/账号注销.jpg" />
            </div>
            <span style="font-size: 20px;margin-left:34% ;color:dimgrey;">注销账号</span>

            <!-- <h2 style="font-size: 20px;margin-left:33% ;color:greenyellow;margin-top: 20px;">√ 已设置</h2> -->
            <h2 style="font-size: 20px;margin-left:14% ;color:dimgrey;margin-top: 20px;">彻底关闭不再使用账号</h2>
            <el-button style="width: 180px;height: 45px;margin-left:15% ;margin-top: 20px; " @click="">注销账号</el-button>
        </el-card>
        <el-card style="float: left;width: 300px;height: 360px;margin-left: 50px;margin-top: 40px;">
            <div align="center" style="margin-top: 20px;">
                <el-image style="width: 100px; height: 100px" src="http://localhost:5008/Image/安全密码.jpg" />
            </div>
            <span style="font-size: 20px;margin-left:34% ;color:dimgrey;">安全密码</span>

            <!-- <h2 style="font-size: 20px;margin-left:33% ;color:greenyellow;margin-top: 20px;">√ 已设置</h2> -->
            <h2 style="font-size: 20px;margin-left:15% ;color:dimgrey;margin-top: 20px;">审批，支付密码设置</h2>
            <el-button style="width: 180px;height: 45px;margin-left:15% ;margin-top: 20px; " @click="">立即设置</el-button>
        </el-card>
    </div>
    <!-- 修改密码 -->
    <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
        <el-form ref="ruleFormRef" style="max-width: 300px; margin-left: 10%" :model="ruleForm" :rules="rules"
            label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="当前密码" prop="Password">
                <el-input v-model="ruleForm.Password" @click="showPassword" show-password placeholder="请输入当前密码" />
            </el-form-item>
            <el-form-item label="新密码" prop="NewPassword">
                <el-input v-model="ruleForm.NewPassword" show-password placeholder="请输入新密码" />
            </el-form-item>
            <el-form-item label="确认新密码" prop="QuePassword">
                <el-input v-model="ruleForm.QuePassword" show-password placeholder="请确认新密码" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" style="width: 100%" @click="submitForm()">
                    确认
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 修改手机号 -->
    <el-dialog v-model="dialogFormVisible2" title="" style="width: 50%;height: 70%;">
        <h2 style=" color: sandybrown;">修改手机号</h2>
        <br>
        <el-image style="width: 500px; height: 30px;margin-left: 60px;" src="http://localhost:5008/Image/手机号流程图.png" />
        <table style="width: 100%;height: 200px;">
            <tr>
                <td style="font-size: 20px;color: sandybrown;">原手机号码</td>
                <td style="font-size: 20px;color: sandybrown;font-weight: bold;">{{ (PhoneNumber.slice(0, 3) + "****" +
                    PhoneNumber.slice(0, 4)) }}</td>
            </tr>
            <tr>
                <td style="font-size: 20px;color: sandybrown;">手机短信验证码</td>
                <td>
                    <el-input v-model="inputCode" style="width: 200px" placeholder="请输入验证码" />
                    <el-button type="primary" style="width:100px;margin-left: 20px"
                        @click="GetPhoneChange(PhoneNumber)">
                        {{ verificationCode }}
                    </el-button>
                    <span v-if="timeLeft < 30 && timeLeft > 0" style="color:darkgray"> 验证码有效期：{{ timeLeft }}秒</span>
                </td>
            </tr>
        </table>
        <span>若原手机号丢失或停用，
            <el-button type="primary" link style="width: 70px">
                请请点击这里
            </el-button>
        </span>
        <el-button type="primary" style="width: 100%" @click="submitCodePhone">
            下一步
        </el-button>
    </el-dialog>
    <el-dialog v-model="dialogFormVisible2_1" title="" style="width: 50%;height: 70%;">
        <h2 style=" color: sandybrown;">修改手机号</h2>
        <br>
        <table style="width: 100%;height: 200px;">
            <tr>
                <td style="font-size: 20px;color: sandybrown;">真实姓名</td>
                <td>
                    <el-input v-model="phoneform.name" style="width: 200px" placeholder="请输入真实" />
                </td>
            </tr>
            <tr>
                <td style="font-size: 20px;color: sandybrown;">身份证号</td>
                <td>
                    <el-input v-model="phoneform.SId" style="width: 200px" placeholder="请输入身份证号" />
                </td>
            </tr>
            <tr>
                <td style="font-size: 20px;color: sandybrown;">手持身份证照片</td>
                <td>
                    <el-upload class="avatar-uploader" action="http://localhost:5008/api/RBACs/UpdateImage"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="phoneform.Images" :src="phoneform.Images" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    请上传免冠手持身份证彩色照片支持image、jpeg、bmp、png、格式
                </td>
            </tr>
            <tr>
                <td style="font-size: 20px;color: sandybrown;">新手机号</td>
                <td>
                    <el-input v-model="phoneform.Phones" style="width: 200px" placeholder="请输入新手机号" />
                </td>
            </tr>
            <tr>
                <td style="font-size: 20px;color: sandybrown;">短信验证码</td>
                <td>
                    <el-input v-model="inputCode" style="width: 200px" placeholder="请输入验证码" />
                    <el-button type="primary" style="width:100px;margin-left: 20px"
                        @click="GetPhoneChange(PhoneNumber)">
                        {{ verificationCode }}
                    </el-button>
                    <span v-if="timeLeft < 30 && timeLeft > 0" style="color:darkgray"> 验证码有效期：{{ timeLeft }}秒</span>
                </td>
            </tr>
        </table>
        <el-button type="primary" @click="submitForm">
            保存
        </el-button>
        <el-button type="primary">
            取消
        </el-button>
    </el-dialog>



</template>

<script setup lang="ts">
import {
    SuccessFilled,
} from '@element-plus/icons-vue'
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
//调用持久化
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
const route = useRoute();
const router = useRouter();

let timer: number | undefined = undefined;  // 定时器
const timeLeft = ref(30);  // 剩余时间
const inputCode = ref('');  // 用户输入的验证码
const verificationCode = ref('点击获取验证码');  // 验证码
const isCountingDown = ref(false);  // 是否在倒计时中
const codeTimestamp = ref<number | undefined>(undefined);  // 验证码生成时间戳
onMounted(() => {
    getEmployeeData()//获取员工信息

})

const handleAvatarSuccess = (url: any) => {
    phoneform.Images = 'http://localhost:5008' + url
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg/bmp/png') {
        ElMessage.error('亲，只能上传jpg/pngbmp/png格式的图片哦！')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片只大小不能超过 2MB!')
        return false
    }
    return true
}
//弹框条件
const dialogFormVisible = ref(false)//修改密码
const dialogFormVisible2 = ref(false)//修改手机号 
const dialogFormVisible2_1 = ref(false)//修改手机号
const dialogFormVisible3 = ref(false)//修改账号注销
const dialogFormVisible4 = ref(false)//安全密码设置

//修改密码
const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
    Password: '',
    NewPassword: '',
    QuePassword: '',
    SMSVerificationCode: '',
});

const phoneform = reactive({
    name: '',
    SId: '',
    Images: '',
    Phones: '',
})

//校验规则
const rules = reactive<FormRules>({
    Password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        //密码和数字组合，长度在 3 到 6 个字符
        {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{3,8}$/,
            message: '密码和数字组合，长度在 3 到 8 个字符',
            trigger: 'blur'
        },
        {
            validator: (rule, value, callback) => {
                if (value != password.value) {
                    callback(new Error('密码错误'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ], NewPassword: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        //密码和数字组合，长度在 3 到 6 个字符
        {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{3,8}$/,
            message: '密码和数字组合，长度在 3 到 8 个字符',
            trigger: 'blur'
        }
    ],
    QuePassword: [
        //去人password 和 NewPassword 是否相同
        {
            validator: (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== ruleForm.NewPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
});
//验证码
const change = (phone: any) => {
    let data = {
        employeeId: counterStore.employeeId,
        phone: phone,
        captcha: "",
        phoneDate: new Date()
    }
    axios.post('http://localhost:5008/api/RBACs/PhoneCaptchaCreate', data).then((res) => {
        if (res.data.code == 0) {
            ElMessage.success('发送成功');
        }

    }).catch((err) => {
        console.log(err);
    })
}

const GetPhoneChange = (phone: any) => {
    codeTimestamp.value = Date.now(); // 记录验证码生成的时间戳
    if (timeLeft.value < 30 && timeLeft.value > 0) {

        ElMessage.warning('请等待' + timeLeft.value + '秒后重试');
        return;

    }
    timeLeft.value = 30; // 重置倒计时
    isCountingDown.value = true;  // 开始倒计时
    // 设置倒计时
    timer = window.setInterval(() => {
        if (timeLeft.value > 0) {
            timeLeft.value--;
        } else {
            clearInterval(timer);  // 倒计时结束，清除定时器
            isCountingDown.value = false;  // 停止倒计时
            verificationCode.value = '点击获取验证码'; // 重置验证码文本
        }
    }, 1000);
    change(phone);//添加验证码
    setTimeout(() => {
        axios.get('http://localhost:5008/api/RBACs/PhoneCaptchaListCommon', {
            params: {
                phone: phone,
                employeeId: counterStore.employeeId,
            }
        }).then((res) => {
            console.log(res.data)
            verificationCode.value = res.data.data[0].captcha//获取验证码
            console.log(verificationCode.value)
        }).catch((err) => {
            console.log(err);
        })
    }, 1000);

}
//校验
const nameRegex = /^[\u4e00-\u9fa5]{2,10}$/; // Only letters and spaces for name
const idRegex = /^[A-Za-z0-9]{6,12}$/; // Alphanumeric and length between 6-12 for SId
const phoneRegex = /^[0-9]{11}$/; // 10-digit phone number
const regex = /^(?:\d{15}|\d{17}[\dXx])$/;
//提交验证码
const submitCodePhone = () => {

    if (!codeTimestamp.value) {
        ElMessage.error('亲先获取取验证码');
        return;
    }
    const currentTime = Date.now();
    const isExpired = (currentTime - codeTimestamp.value) > 30000; // 超过30秒即过期
    if (isExpired) {
        alert('验证码已过期，请重新获取');
        return;
    }
    axios.post("http://localhost:5008/api/RBACs/CaptchaList", {
        captcha: inputCode.value,
        phone: PhoneNumber.value
    }).then((res) => {
        if (res.data.code == 0) {
            ElMessage.success('验证码正确');
            timeLeft.value = 30;
            clearInterval(timer);  // 倒计时结束，清除定时器
            isCountingDown.value = false;  // 停止倒计时
            dialogFormVisible2.value = false;
            dialogFormVisible2_1.value = true;
            verificationCode.value = '点击获取验证码'; // 重置验证码文本  
            inputCode.value = '';


        }
        else {
            ElMessage.error('验证码错误');
        }
    })
}





const submitForm = async () => {
    if (!nameRegex.test(phoneform.name)) {
        ElMessage.error('姓名格式不正确');
        return;
    }

    // Validate SId
    if (!regex.test(phoneform.SId)) {
        ElMessage.error('身份证格式不正确');
        return;
    }

    // Validate Phones
    if (!phoneRegex.test(phoneform.Phones)) {
        ElMessage.error('手机号格式不正确');
        return;
    }

    if (!codeTimestamp.value) {
        ElMessage.error('亲先获取取验证码');
        return;
    }
    const currentTime = Date.now();
    const isExpired = (currentTime - codeTimestamp.value) > 30000; // 超过30秒即过期
    if (isExpired) {
        alert('验证码已过期，请重新获取');
        return;
    }
    axios.post("http://localhost:5008/api/RBACs/CaptchaList", {
        captcha: inputCode.value,
        phone: PhoneNumber.value
    }).then((res) => {
        if (res.data.code == 0) {
            axios
                .get('http://localhost:5008/api/RBACs/PhoneUpdate', {
                    params: {
                        employeeId: counterStore.employeeId,
                        Phone: phoneform.Phones
                    }
                })
                .then((res) => {
                    console.log(res.data)
                    if (res.data.code == 0) {
                        ElMessage.success('修改成功');
                        timeLeft.value = 30;
                        clearInterval(timer);  // 倒计时结束，清除定时器
                        isCountingDown.value = false;  // 停止倒计时  
                        dialogFormVisible2_1.value = false;
                        verificationCode.value = '点击获取验证码'; // 重置验证码文本  
                        inputCode.value = '';
                        getEmployeeData();
                    } else {
                        ElMessage.error('修改失败');
                    }
                });
        }
        else {
            ElMessage.error('验证码错误');
        }
    })


};

//获取手机验证码
//获取个人信息
const PhoneNumber = ref("");
const password = ref("");
const getEmployeeData = () => {
    var result: any = ref({})
    result.employeeId = counterStore.employeeId,
        axios.post("http://localhost:5008/api/RBACs/DetailEmployee", result).then(res => {
            PhoneNumber.value = res.data.item.phoneNumber
            password.value = res.data.item.password
        })
}

//判断密码是否正确
const showPassword = async () => {
    if (password.value == ruleForm.Password) {

    }
}

// 组件销毁时清除定时器
onBeforeUnmount(() => {
    if (timer !== undefined) {
        clearInterval(timer);
    }
});




</script>

<style scoped>
.my-form-item .el-form-item__label {
    color: orange;
}

.avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
</style>